/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * taggingService.java
 *
 * Created on Jul 26, 2010, 1:42:51 PM
 */

package crfsvm.crf.een_phuong;

import java.nio.ByteOrder;
import javax.imageio.stream.IIOByteBuffer;
import javax.swing.UIManager;
import org.jdesktop.application.Action;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import javax.swing.text.Document;
import javax.swing.text.Highlighter;
import javax.swing.text.Highlighter.HighlightPainter;
import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter;
import javax.swing.text.JTextComponent;
import java.util.Date;
import java.util.StringTokenizer;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;

/**
 *
 * @author Thien
 */
public class taggingService extends javax.swing.JFrame {

    /** Creates new form taggingService */
    public taggingService() {
        try
        {
            this.setTitle("Chunking and Tagging Application Ver 1.0 By Thien Huu Nguyen (Hanoi University of Technology)");
            this.setIconImage(Toolkit.getDefaultToolkit().getImage("." + File.separator + "src" + File.separator + "een_phuong" + File.separator + "resources" + File.separator + "taggingService.JPG"));
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            //UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
            //UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
            initComponents();
            setEnableButtonTag(false);
            setVisibleButtonAll(false);
            buttonReload.setVisible(false);
            buttonSave.setVisible(false);
            checkBoxChoose.setVisible(false);
            buttonPer.setForeground(Color.CYAN);
            buttonLoc.setForeground(Color.LIGHT_GRAY);
            buttonOrg.setForeground(Color.MAGENTA);
            buttonNP.setForeground(Color.green);
            this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
            textArea.getDocument().addDocumentListener(new DocumentListener() {

                public void insertUpdate(DocumentEvent e) {
                    changedUpdate(e);
                }

                public void removeUpdate(DocumentEvent e) {
                    changedUpdate(e);
                }

                public void changedUpdate(DocumentEvent e) {

                    if (checkBoxMode.isSelected())
                    {
                        if (checkBoxChoose.isSelected())
                                setEnableButtonTagAll(true);
                            else
                            {
                                buttonNP.setEnabled(true);
                                buttonUntag.setEnabled(true);
                                buttonSave.setEnabled(true);
                                buttonReload.setEnabled(true);
                            }
                    }
                }
            });
        }
        catch (Exception e)
        {
            labelStatus.setText("Can not update Look and Feel: " + e);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        labelPath = new javax.swing.JLabel();
        textFieldPath = new javax.swing.JTextField();
        buttonPer = new javax.swing.JButton();
        buttonLoc = new javax.swing.JButton();
        buttonOrg = new javax.swing.JButton();
        buttonSave = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        textArea = new javax.swing.JTextArea();
        buttonBrowse = new javax.swing.JButton();
        buttonUntag = new javax.swing.JButton();
        checkBoxEdit = new javax.swing.JCheckBox();
        labelStatus = new javax.swing.JLabel();
        buttonReload = new javax.swing.JButton();
        buttonSaveAs = new javax.swing.JButton();
        checkBoxMode = new javax.swing.JCheckBox();
        checkBoxChoose = new javax.swing.JCheckBox();
        buttonNP = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("Form"); // NOI18N
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance().getContext().getResourceMap(taggingService.class);
        labelPath.setText(resourceMap.getString("labelPath.text")); // NOI18N
        labelPath.setName("labelPath"); // NOI18N

        textFieldPath.setEditable(false);
        textFieldPath.setText(resourceMap.getString("textFieldPath.text")); // NOI18N
        textFieldPath.setName("textFieldPath"); // NOI18N
        textFieldPath.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseExited(java.awt.event.MouseEvent evt) {
                textFieldPathMouseExited(evt);
            }
        });
        textFieldPath.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textFieldPathActionPerformed(evt);
            }
        });

        buttonPer.setMnemonic('P');
        buttonPer.setText(resourceMap.getString("buttonPer.text")); // NOI18N
        buttonPer.setToolTipText(resourceMap.getString("buttonPer.toolTipText")); // NOI18N
        buttonPer.setName("buttonPer"); // NOI18N
        buttonPer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonPerActionPerformed(evt);
            }
        });

        buttonLoc.setMnemonic('L');
        buttonLoc.setText(resourceMap.getString("buttonLoc.text")); // NOI18N
        buttonLoc.setToolTipText(resourceMap.getString("buttonLoc.toolTipText")); // NOI18N
        buttonLoc.setName("buttonLoc"); // NOI18N
        buttonLoc.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonLocActionPerformed(evt);
            }
        });

        buttonOrg.setMnemonic('O');
        buttonOrg.setText(resourceMap.getString("buttonOrg.text")); // NOI18N
        buttonOrg.setToolTipText(resourceMap.getString("buttonOrg.toolTipText")); // NOI18N
        buttonOrg.setActionCommand(resourceMap.getString("buttonOrg.actionCommand")); // NOI18N
        buttonOrg.setName("buttonOrg"); // NOI18N
        buttonOrg.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonOrgActionPerformed(evt);
            }
        });

        buttonSave.setText(resourceMap.getString("buttonSave.text")); // NOI18N
        buttonSave.setToolTipText(resourceMap.getString("buttonSave.toolTipText")); // NOI18N
        buttonSave.setEnabled(false);
        buttonSave.setName("buttonSave"); // NOI18N
        buttonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSaveActionPerformed(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        textArea.setColumns(20);
        textArea.setEditable(false);
        textArea.setLineWrap(true);
        textArea.setRows(5);
        textArea.setWrapStyleWord(true);
        textArea.setName("textArea"); // NOI18N
        jScrollPane1.setViewportView(textArea);

        buttonBrowse.setText(resourceMap.getString("buttonBrowse.text")); // NOI18N
        buttonBrowse.setToolTipText(resourceMap.getString("buttonBrowse.toolTipText")); // NOI18N
        buttonBrowse.setName("buttonBrowse"); // NOI18N
        buttonBrowse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonBrowseClicked(evt);
            }
        });

        buttonUntag.setMnemonic('U');
        buttonUntag.setText(resourceMap.getString("buttonUntag.text")); // NOI18N
        buttonUntag.setToolTipText(resourceMap.getString("buttonUntag.toolTipText")); // NOI18N
        buttonUntag.setName("buttonUntag"); // NOI18N
        buttonUntag.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonUntagActionPerformed(evt);
            }
        });

        checkBoxEdit.setText(resourceMap.getString("checkBoxEdit.text")); // NOI18N
        checkBoxEdit.setToolTipText(resourceMap.getString("checkBoxEdit.toolTipText")); // NOI18N
        checkBoxEdit.setName("checkBoxEdit"); // NOI18N
        checkBoxEdit.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                checkBoxEditItemStateChanged(evt);
            }
        });

        labelStatus.setText(resourceMap.getString("labelStatus.text")); // NOI18N
        labelStatus.setName("labelStatus"); // NOI18N

        buttonReload.setText(resourceMap.getString("buttonReload.text")); // NOI18N
        buttonReload.setToolTipText(resourceMap.getString("buttonReload.toolTipText")); // NOI18N
        buttonReload.setEnabled(false);
        buttonReload.setName("buttonReload"); // NOI18N
        buttonReload.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonReloadActionPerformed(evt);
            }
        });

        buttonSaveAs.setText(resourceMap.getString("buttonSaveAs.text")); // NOI18N
        buttonSaveAs.setToolTipText(resourceMap.getString("buttonSaveAs.toolTipText")); // NOI18N
        buttonSaveAs.setName("buttonSaveAs"); // NOI18N
        buttonSaveAs.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSaveAsActionPerformed(evt);
            }
        });

        checkBoxMode.setText(resourceMap.getString("checkBoxMode.text")); // NOI18N
        checkBoxMode.setToolTipText(resourceMap.getString("checkBoxMode.toolTipText")); // NOI18N
        checkBoxMode.setName("checkBoxMode"); // NOI18N
        checkBoxMode.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                checkBoxModeActionPerformed(evt);
            }
        });

        checkBoxChoose.setSelected(true);
        checkBoxChoose.setText(resourceMap.getString("checkBoxChoose.text")); // NOI18N
        checkBoxChoose.setToolTipText(resourceMap.getString("checkBoxChoose.toolTipText")); // NOI18N
        checkBoxChoose.setName("checkBoxChoose"); // NOI18N
        checkBoxChoose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                checkBoxChooseActionPerformed(evt);
            }
        });

        buttonNP.setMnemonic('N');
        buttonNP.setText(resourceMap.getString("buttonNP.text")); // NOI18N
        buttonNP.setToolTipText(resourceMap.getString("buttonNP.toolTipText")); // NOI18N
        buttonNP.setEnabled(false);
        buttonNP.setName("buttonNP"); // NOI18N
        buttonNP.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonNPActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(labelStatus)
                .addContainerGap(710, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(checkBoxMode)
                    .addComponent(checkBoxChoose))
                .addGap(24, 24, 24)
                .addComponent(labelPath)
                .addGap(18, 18, 18)
                .addComponent(textFieldPath, javax.swing.GroupLayout.PREFERRED_SIZE, 326, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(buttonBrowse)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(2, 2, 2)
                .addComponent(checkBoxEdit)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(buttonPer)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(buttonLoc)
                .addGap(2, 2, 2)
                .addComponent(buttonNP)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonOrg)
                .addGap(18, 18, 18)
                .addComponent(buttonUntag)
                .addGap(24, 24, 24)
                .addComponent(buttonReload)
                .addGap(18, 18, 18)
                .addComponent(buttonSave)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(buttonSaveAs)
                .addContainerGap(23, Short.MAX_VALUE))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 751, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(buttonBrowse)
                            .addComponent(textFieldPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(labelPath)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(checkBoxMode)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(checkBoxChoose)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonUntag)
                    .addComponent(buttonSave)
                    .addComponent(buttonReload)
                    .addComponent(buttonSaveAs)
                    .addComponent(buttonPer)
                    .addComponent(buttonOrg)
                    .addComponent(buttonLoc)
                    .addComponent(buttonNP)
                    .addComponent(checkBoxEdit))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 417, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(labelStatus))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonBrowseClicked(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonBrowseClicked
        // TODO add your handling code here:
            //String pa;
            //if (!checkBoxMode.isSelected())
            //    wd = "D:\\Document\\Informatics\\IE\\From Thani\\Data\\MapTextForm";
            //else
            //    wd = "D:\\Document\\Informatics\\IE\\From Thani\\Data\\TaggedTexts";
        try
        {
            File ff = new File(".");
            String fileDes = ff.getCanonicalPath() + File.separator + "data" + File.separator + "labs" + File.separator;
            Date d = new Date();
            fileDes += d.getTime() + "_";
            String wd = ""; System.getProperty("user.dir");
            wd = "D:\\Document\\Informatics\\IE\\From Thani\\TrainingDoc";
            JFileChooser choose = new JFileChooser(wd);
            ExampleFileFilter filter = new ExampleFileFilter("txt","txt File");
            choose.addChoosableFileFilter(filter);
            
            int f = choose.showOpenDialog(this);
            if (f == JFileChooser.APPROVE_OPTION)
            {
                File inFile = choose.getSelectedFile();
                textFieldPath.setText(inFile.getPath());
                fileDes += inFile.getName();
                if (checkBoxChoose.isSelected())
                    copyFile(inFile.getPath(), fileDes);
                if (checkBoxMode.isSelected())
                    loadFile(textFieldPath.getText());
                else
                {
                    textArea.setText(vnTagger(textFieldPath.getText()));
                    setEnableButtonTagAll(false);
                    buttonNP.setEnabled(false);
                    labelStatus.setText("Chunking Successfully!");
                }
                    
            }
        }
        catch (Exception ex)
        {
            System.out.println("Error: " + ex);
        }
    }//GEN-LAST:event_buttonBrowseClicked

    private void buttonPerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonPerActionPerformed
        // TODO add your handling code here:
        try
        {
                int start = textArea.getSelectionStart();
                int end = textArea.getSelectionEnd();

                textArea.insert("<per> ", start);
                textArea.insert(" </per>", end + 6);

                textArea.select(start + 6, end + 6);
                
                Highlighter hili = textArea.getHighlighter();
                hili.addHighlight(start + 6, end + 6, (HighlightPainter) new DefaultHighlightPainter(Color.CYAN));

                labelStatus.setText("Person Tagged:  " + textArea.getSelectedText());
                buttonSave.setEnabled(true);
                buttonReload.setEnabled(true);
        }
        catch (Exception e)
        {
            labelStatus.setText("Error: " + e);
        }
    }//GEN-LAST:event_buttonPerActionPerformed

    private void buttonLocActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonLocActionPerformed
        // TODO add your handling code here:
        try
        {
                int start = textArea.getSelectionStart();
                int end = textArea.getSelectionEnd();

                textArea.insert("<loc> ", start);
                textArea.insert(" </loc>", end + 6);

                textArea.select(start + 6, end + 6);

                Highlighter hili = textArea.getHighlighter();
                hili.addHighlight(start + 6, end + 6, (HighlightPainter) new DefaultHighlightPainter(Color.LIGHT_GRAY));

                labelStatus.setText("Location Tagged:  " + textArea.getSelectedText());
                buttonSave.setEnabled(true);
                buttonReload.setEnabled(true);
        }
        catch (Exception e)
        {
            labelStatus.setText("Error: " + e);
        }
    }//GEN-LAST:event_buttonLocActionPerformed

    private void buttonOrgActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonOrgActionPerformed
        // TODO add your handling code here:
        try
        {
                int start = textArea.getSelectionStart();
                int end = textArea.getSelectionEnd();

                textArea.insert("<org> ", start);
                textArea.insert(" </org>", end + 6);

                textArea.select(start + 6, end + 6);

                Highlighter hili = textArea.getHighlighter();
                hili.addHighlight(start + 6, end + 6, (HighlightPainter) new DefaultHighlightPainter(Color.MAGENTA));

                labelStatus.setText("Organization Tagged:  " + textArea.getSelectedText());
                buttonSave.setEnabled(true);
                buttonReload.setEnabled(true);
        }
        catch (Exception e)
        {
            labelStatus.setText("Error: " + e);
        }
    }//GEN-LAST:event_buttonOrgActionPerformed

    private void buttonUntagActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonUntagActionPerformed
        // TODO add your handling code here:
        try
        {
                int start = textArea.getSelectionStart();
                int end = textArea.getSelectionEnd();
                String selected = textArea.getSelectedText(), tag = "";
                boolean checkStart = false;
                if (checkBoxChoose.isSelected())
                {
                    for (int i = 0; i < tags.length; i++)
                        if (selected.startsWith("<" + tags[i] + "> "))
                        {
                            checkStart = true;
                            tag = tags[i];
                            break;
                        }
                    if (!checkStart) return;
                    if (selected.endsWith(" </" + tag + ">"))
                    {
                        textArea.replaceRange("", start, start + tag.length() + 3);
                        textArea.replaceRange("",end - 2*tag.length() - 7,end - tag.length() - 3);
                        textArea.select(start, end - 2*tag.length() - 7);
                        labelStatus.setText(tag + " Untagged:  " + textArea.getSelectedText());
                        buttonSave.setEnabled(true);
                        buttonReload.setEnabled(true);
                    }
                }
                else
                {
                    for (int i = 0; i < chunks.length; i++)
                        if (selected.startsWith("<" + chunks[i] + "> "))
                        {
                            checkStart = true;
                            tag = chunks[i];
                            break;
                        }
                    if (!checkStart) return;
                    if (selected.endsWith(" </" + tag + ">"))
                    {
                        textArea.replaceRange("", start, start + tag.length() + 3);
                        textArea.replaceRange("",end - 2*tag.length() - 7,end - tag.length() - 3);
                        textArea.select(start, end - 2*tag.length() - 7);
                        labelStatus.setText(tag + " Untagged:  " + textArea.getSelectedText());
                        buttonSave.setEnabled(true);
                        buttonReload.setEnabled(true);
                    }
                }
        }
        catch (Exception e)
        {
            labelStatus.setText("Error: " + e);
        }
    }//GEN-LAST:event_buttonUntagActionPerformed

    private void checkBoxEditItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_checkBoxEditItemStateChanged

        // TODO add your handling code here:
        textArea.setEditable(!textArea.isEditable());
    }//GEN-LAST:event_checkBoxEditItemStateChanged

    private void buttonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSaveActionPerformed
        // TODO add your handling code here:
        if(JOptionPane.showConfirmDialog(this, "This action will overwrite your old file, do you want to continue? (Press Yes to continue ,Press No to abort)","WARNING", JOptionPane.WARNING_MESSAGE, JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
            {
               saveTextArea(textFieldPath.getText());
            }
    }//GEN-LAST:event_buttonSaveActionPerformed

    private void buttonReloadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonReloadActionPerformed
        // TODO add your handling code here:
        File f = new File(textFieldPath.getText());
        if (f.isFile())
        {
            buttonSaveActionPerformed(evt);
            loadFile(textFieldPath.getText());
        }
        else
        {
            labelStatus.setText("File Path is incorrect!");
        }
    }//GEN-LAST:event_buttonReloadActionPerformed

    private void textFieldPathActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textFieldPathActionPerformed
        // TODO add your handling code here:
        try
        {
            File f = new File(textFieldPath.getText());
            File current = new File(".");
            if (!f.isFile())
            {
                labelStatus.setText("File Path is incorrect! Default file is replaced!");
                Date date = new Date();
                textFieldPath.setText(current.getCanonicalPath() + File.separator + date + ".txt");
                buttonSave.setEnabled(true);
                buttonReload.setEnabled(true);
            }
        }
        catch (Exception e)
        {
            labelStatus.setText("Error: " + e);
        }
    }//GEN-LAST:event_textFieldPathActionPerformed

    private void textFieldPathMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_textFieldPathMouseExited
        // TODO add your handling code here:
        try
        {
            File f = new File(textFieldPath.getText());
            File current = new File(".");
            if (!f.isFile())
            {
                labelStatus.setText("File Path is incorrect! Default file is replaced!");
                Date date = new Date();
                textFieldPath.setText(current.getCanonicalPath() + File.separator + "temp_" + date.getTime() + ".txt");
                if (checkBoxMode.isSelected())
                {
                    buttonSave.setEnabled(true);
                    buttonReload.setEnabled(true);
                }
            }
        }
        catch (Exception e)
        {
            labelStatus.setText("Error: " + e);
        }
    }//GEN-LAST:event_textFieldPathMouseExited

    private void buttonSaveAsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSaveAsActionPerformed
        // TODO add your handling code here:
            //String wd = System.getProperty("user.dir");
            //String wd = "D:\\Document\\Informatics\\IE\\From Thani\\Data\\TaggedTexts";
            String wd = ""; System.getProperty("user.dir");
            wd = "D:\\Document\\Informatics\\IE\\From Thani\\TrainingDoc";
            JFileChooser fc = new JFileChooser(wd);
            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int rc = fc.showSaveDialog(this);
            if (rc == JFileChooser.APPROVE_OPTION)
            {
                    File file = fc.getSelectedFile();
                    String filename = file.getAbsolutePath();
                    saveTextArea(filename);
            }
    }//GEN-LAST:event_buttonSaveAsActionPerformed

    private void checkBoxModeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkBoxModeActionPerformed
        // TODO add your handling code here:
        checkBoxModeListener();
    }//GEN-LAST:event_checkBoxModeActionPerformed

    private void checkBoxChooseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkBoxChooseActionPerformed
        // TODO add your handling code here:
        checkBoxChooseListener();
    }//GEN-LAST:event_checkBoxChooseActionPerformed

    private void buttonNPActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonNPActionPerformed
        // TODO add your handling code here:
        try
        {
                int start = textArea.getSelectionStart();
                int end = textArea.getSelectionEnd();

                textArea.insert("<NP> ", start);
                textArea.insert(" </NP>", end + 5);

                textArea.select(start + 5, end + 5);

                Highlighter hili = textArea.getHighlighter();
                hili.addHighlight(start + 5, end + 5, (HighlightPainter) new DefaultHighlightPainter(Color.green));

                labelStatus.setText("NP Tagged:  " + textArea.getSelectedText());
                buttonSave.setEnabled(true);
                buttonReload.setEnabled(true);
        }
        catch (Exception e)
        {
            labelStatus.setText("Error: " + e);
        }
    }//GEN-LAST:event_buttonNPActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        if(JOptionPane.showConfirmDialog(this, "Do you want to exit the work? (Press Yes to exit ,Press No to come back and save your work)","WARNING", JOptionPane.WARNING_MESSAGE, JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
            {
                dispose();
            }

    }//GEN-LAST:event_formWindowClosing

    public void saveTextArea(String file)
    {
        try
        {
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
            out.write(textArea.getText());
            out.close();
            buttonSave.setEnabled(false);
            labelStatus.setText("Save SUCCESSFULLY!");
        }
        catch (Exception e)
        {
              buttonSave.setEnabled(false);
              labelStatus.setText("Save UNSUCCESSFULLY!: " + e);
        }
    }

    public void highlightTag(String text, Highlighter hili, String tag, Color color)
    {
        try
        {
            HighlightPainter colorHiLi = (HighlightPainter) new DefaultHighlightPainter(color);
            int posStart = 0;
            int posEnd = 0;
            String start = "<" + tag + "> ";
            String end = " </" + tag + ">";
            while ((posStart = text.indexOf(start, posStart)) >= 0)
            {
                posEnd = text.indexOf(end, posStart);
                hili.addHighlight(posStart + tag.length() + 3, posEnd, colorHiLi);
                posStart = posEnd + tag.length() + 3;
            }
        }
        catch (Exception e)
        {
            labelStatus.setText("Error: " + e);
        }
    }

    public void traceDone(String text, Highlighter hili)
    {
        try
        {
            ArrayList<Object> indexs = new ArrayList<Object>();
            int lineStart = 0, lineEnd = 0, posLine = 0, maxPos = 0;
            while ((posLine = text.indexOf('\n', posLine)) >= 0)
            {
                lineStart = lineEnd;
                lineEnd = posLine;
                int[] arr = {lineStart, lineEnd - 1};
                indexs.add(arr);
                posLine++;
            }

            if (checkBoxChoose.isSelected())
            {
                for (int i = 0; i < tags.length; i++)
                {
                    int result = positionLastTag(text, tags[i], indexs);
                    if (result > maxPos) maxPos = result;
                }
            }
            else
            {
                for (int i = 0; i < chunks.length; i++)
                {
                    int result = positionLastTag(text, chunks[i], indexs);
                    if (result > maxPos) maxPos = result;
                }
            }
            int[] array = (int[]) indexs.get(maxPos);
            hili.addHighlight(array[0], array[1], (HighlightPainter) new DefaultHighlightPainter(Color.YELLOW));
        }
        catch (Exception e)
        {
            labelStatus.setText("Error: " + e);
        }
    }

    public int positionLastTag(String text, String tag, ArrayList<Object> arr)
    {
            int pos = 0, prepos = 0, result = -1;
            while ((pos = text.indexOf(" <" + tag + ">", pos)) >= 0)
                {
                    prepos = pos;
                    pos++;
                }
            for (int i = 0; i < arr.size(); i++)
            {
                int[] array = (int[]) arr.get(i);
                if ((array[0] <= prepos) && (array[1] >= prepos))
                {
                    return i;
                }
            }
            return result;
    }

    public void setEnableButtonTag(boolean state)
    {
        buttonPer.setEnabled(state);
        buttonLoc.setEnabled(state);
        buttonOrg.setEnabled(state);
        buttonUntag.setEnabled(state);
    }

    public void setEnableButtonTagAll(boolean state)
    {
        setEnableButtonTag(state);
        buttonReload.setEnabled(state);
        buttonSave.setEnabled(state);
    }

    public void setVisibleButtonTag(boolean state)
    {
        buttonPer.setVisible(state);
        buttonLoc.setVisible(state);
        buttonOrg.setVisible(state);
    }

    public void setVisibleButtonAll(boolean state)
    {
        setVisibleButtonTag(state);
        buttonNP.setVisible(state);
        buttonUntag.setVisible(state);
    }

    public void loadFile(String file)
    {
            textArea.setText("");
            try
            {
                BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));

                String line;

                while ((line = in.readLine()) != null)
                {
                    if (checkBoxChoose.isSelected())
                        textArea.append(eliminateTags(line, chunks) + "\n");
                    else
                        textArea.append(eliminateTags(line, tags) + "\n");
                }

                Document doc = textArea.getDocument();
                String text = doc.getText(0, doc.getLength());
                Highlighter hili = textArea.getHighlighter();

                if (checkBoxChoose.isSelected())
                {
                    for (int i = 0; i < tags.length; i++)
                    {
                        highlightTag(text, hili, tags[i], colors[i]);
                    }
                }
                else
                {
                    for (int i = 0; i < chunks.length; i++)
                    {
                        highlightTag(text, hili, chunks[i], colorsChunk[i]);
                    }
                }
                traceDone(text, hili);

                in.close();
                buttonSave.setEnabled(false);
                buttonReload.setEnabled(false);
                if (checkBoxChoose.isSelected())
                {
                    setEnableButtonTag(true);
                }
                else
                {
                    buttonNP.setEnabled(true);
                    buttonUntag.setEnabled(true);
                }
            }
            catch (Exception ex)
            {
                labelStatus.setText("Can not open file " + textFieldPath.getName() + ": " + ex);
            }
    }
    public void checkBoxChooseListener()
    {
        if (checkBoxChoose.isSelected())
        {
            int choi = JOptionPane.showConfirmDialog(this, "Do you want to save the work you did? (Press OK to come back and save it by yourself, Press Cancel to continue WITHOUT saving anything?","WARNING",JOptionPane.WARNING_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
            if (choi != JOptionPane.OK_OPTION)
            {
                textFieldPath.setText("");
                textArea.setText("");
                setVisibleButtonTag(true);
                buttonNP.setVisible(false);
                setEnableButtonTagAll(false);
                buttonNP.setEnabled(false);
            }
            else
                checkBoxChoose.setSelected(false);
        }
        else
        {
            int choi = JOptionPane.showConfirmDialog(this, "Do you want to save the work you did? (Press OK to come back and save it by yourself, Press Cancel to continue WITHOUT saving anything?","WARNING",JOptionPane.WARNING_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
            if (choi != JOptionPane.OK_OPTION)
            {
                textFieldPath.setText("");
                textArea.setText("");
                setVisibleButtonTag(false);
                setEnableButtonTagAll(false);
                buttonNP.setVisible(true);
                buttonNP.setEnabled(false);
            }
            else
                checkBoxChoose.setSelected(true);
        }
    }

    public void checkBoxModeListener()
    {
        if (checkBoxMode.isSelected())
        {
                int choice = JOptionPane.showConfirmDialog(this, "Do you want to save the result?", "WARNING", JOptionPane.WARNING_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
                if (choice == JOptionPane.OK_OPTION)
                {
                    String wd = System.getProperty("user.dir");
                    JFileChooser fc = new JFileChooser(wd);
                    fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                    int rc = fc.showSaveDialog(this);
                    if (rc == JFileChooser.APPROVE_OPTION)
                    {
                            File file = fc.getSelectedFile();
                            String filename = file.getAbsolutePath();
                            saveTextArea(filename);
                    }
                }
                textFieldPath.setText("");
                textArea.setText("");
                checkBoxChoose.setVisible(true);
                buttonUntag.setVisible(true);
                buttonReload.setVisible(true);
                buttonSave.setVisible(true);
                setEnableButtonTagAll(false);
                buttonNP.setEnabled(false);
                if (checkBoxChoose.isSelected())
                {
                    setVisibleButtonTag(true);
                    buttonNP.setVisible(false);
                }
                else
                {
                    setVisibleButtonTag(false);
                    buttonNP.setVisible(true);
                }
        }

        else 
        {
            int choi = JOptionPane.showConfirmDialog(this, "Do you want to save the work you did? (Press OK to come back and save it by yourself, Press Cancel to continue WITHOUT saving anything?","WARNING",JOptionPane.WARNING_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
            if (choi != JOptionPane.OK_OPTION)
            {
                textFieldPath.setText("");
                textArea.setText("");
                buttonReload.setVisible(false);
                buttonSave.setVisible(false);
                setEnableButtonTagAll(false);
                buttonNP.setEnabled(false);
                checkBoxChoose.setVisible(false);
                setVisibleButtonAll(false);
            }
            else
                checkBoxMode.setSelected(true);
        }
    }

    public String vnTagger(String filename)
    {
        Runtime rt = Runtime.getRuntime();
        Process process = null;
        String dir = "." + File.separator + "vnTagger" + File.separator + "vnTagger.bat";
        String fileSource = "tempTagging.service", fileDestination = "resultTagging.service";
        try
        {
            File f = new File(".");
            fileSource = f.getCanonicalPath() + File.separator + fileSource;
            fileDestination = f.getCanonicalPath() + File.separator + fileDestination;
            try
            {
                copyFile(filename, fileSource);
            }
            catch(Exception e)
            {
                return e.toString();
            }
            //System.out.println("Starting....\n + source " + fileSource + " \nDes: " + fileDestination);
            process = rt.exec(dir + " -i " + fileSource + " -o " + fileDestination + " -u" + " -p");
            
            process.waitFor();
            //System.out.println("Done!");

            f = new File(fileSource);
            f.delete();

            return tokenizeVietnamese.seperateSentencesInString(modifyvnTagger(fileDestination, true));
            //return "Done!!!!!!!!!!!!";
        }
        catch (Exception ex)
        {
            System.out.println("Error: " + ex);
            return ex.toString();
        }
    }

    public String modifyvnTagger(String fileSource, boolean delete)
    {
        String[] punctuations = {".", "," , "!", "(", ")", "[", "]", "{", "}", "$", "?", "@", "\"", "-", "/", "...", ":", "'", ";"};

        try
        {
            String line = "";
            String ret = "";

            BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(fileSource), "UTF-8"));

            while ((line = in.readLine()) != null) {
                StringTokenizer lineTknr = new StringTokenizer(line, " ");

                while (lineTknr.hasMoreTokens())
                {
                    line = lineTknr.nextToken();

                    int i = line.lastIndexOf("/");
                    line = line.substring(0, i);

                    if (line.indexOf("_") != 0)
                    {
                        line = line.replaceAll("_", " ");
                    }
                    line = "[" + line + "]";

                    char c = line.charAt(1);
                    int ascii = (int) c;

                    if (ascii != 65279)
                    {
                        String toAdd = checkPunctuation(punctuations, line);
                        if (toAdd.length() != 0)
                        {
                            ret += toAdd + " ";
                        }
                        else
                        {
                            ret += line + " ";
                        }
                    }
                }
                if (ret.length() != 1)
                {
                    ret += "\n" + "\n";
                }
            }

            in.close();
            File toDelete = new File(fileSource);
            if (delete)
                toDelete.delete();

            return ret;
        }
        catch (Exception ex)
        {
            System.out.println("Error: " + ex);
            return "";
        }
    }

    public String checkPunctuation(String[] punctuations, String line)
    {
        String result = "";
        for (int i = 0; i < punctuations.length; i++)
            if (("[" + punctuations[i] + "]").equals(line))
            {
                result = punctuations[i];
                break;
            }
        return result;
    }

    public void copyFile(String srFile, String dtFile)
    {
        try {
            File f1 = new File(srFile);
            File f2 = new File(dtFile);
            InputStream in = new FileInputStream(f1);
            OutputStream out = new FileOutputStream(f2);

            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        }
        catch (IOException e)
        {
            System.out.println(e.getMessage());
        }
    }

    public String eliminateTags(String data, String[] tags)
    {
        for (int i = 0;i < tags.length; i++)
        {
            data = data.replace("<" + tags[i] + "> ", "");
            data = data.replace(" </" + tags[i] + ">", "");
        }
        for (int i = 0;i < tags.length; i++)
        {
            data = data.replace("<" + tags[i] + ">", "");
            data = data.replace("</" + tags[i] + ">", "");
        }
        return data;
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new taggingService().setVisible(true);
            }
        });
    }

    private String[] tags = {"per", "loc", "org"};
    private String[] chunks = {"NP"};
    private Color[] colors = { Color.CYAN, Color.LIGHT_GRAY, Color.MAGENTA};
    private Color[] colorsChunk = {Color.green};
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonBrowse;
    private javax.swing.JButton buttonLoc;
    private javax.swing.JButton buttonNP;
    private javax.swing.JButton buttonOrg;
    private javax.swing.JButton buttonPer;
    private javax.swing.JButton buttonReload;
    private javax.swing.JButton buttonSave;
    private javax.swing.JButton buttonSaveAs;
    private javax.swing.JButton buttonUntag;
    private javax.swing.JCheckBox checkBoxChoose;
    private javax.swing.JCheckBox checkBoxEdit;
    private javax.swing.JCheckBox checkBoxMode;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel labelPath;
    private javax.swing.JLabel labelStatus;
    private javax.swing.JTextArea textArea;
    private javax.swing.JTextField textFieldPath;
    // End of variables declaration//GEN-END:variables

}
